<template>
  <el-dialog :title="$t('collectDetail.sendMessage')" :visible.sync="showState" :before-close="handleClose" :close-on-click-modal="false" width="80%">
    <el-button-group>
      <el-button :type="type === 1 ? 'primary' : ''" @click="setType(1)">{{ $t('collectDetail.friendInfo') }}</el-button>
      <el-button :type="type === 2 ? 'primary' : ''" @click="setType(2)">{{ $t('collectDetail.addressBook') }}</el-button>
    </el-button-group>
    <el-row style="margin-top: 20px">
      <el-table
        ref="multipleTable"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        :data="type === 1 ? userContactData : phoneData"
        border
        :stripe="true"
        tooltip-effect="dark"
        height="263"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          fixed="left"
          type="selection"
          width="55"
        />
        <el-table-column
          fixed="left"
          prop="contactName"
          :label="$t('collectDetail.name')"
          min-width="150"
        />
        <el-table-column
          fixed="left"
          prop="contactPhone"
          :label="$t('collectDetail.phone')"
          min-width="150"
        />
        <el-table-column
          prop="phoneNumStatus"
          :label="$t('authModule.contactPerson.status')"
        >
          <template slot-scope="scope">
            {{ scope.row['phoneNumStatus'] !== null ? $t('authModule.contactPerson.state')[scope.row['phoneNumStatus']] : '' }}
          </template>
        </el-table-column>
        <el-table-column
          prop="modifyTime"
          :label="$t('authModule.contactPerson.lastUpdated')"
          min-width="170"
        />
        <el-table-column
          prop="modifyOperatorName"
          :label="$t('authModule.contactPerson.updater')"
          min-width="150"
        />
        <el-table-column
          :label="$t('authModule.contactPerson.operation')"
          min-width="250"
        >
          <template slot-scope="scope">
            <el-button type="text" @click="setContactState(scope.row, 1)">{{ $t('authModule.contactPerson.connectedNot') }}</el-button>
            <el-button type="text" @click="setContactState(scope.row, 2)">{{ $t('authModule.contactPerson.shutdown') }}</el-button>
            <el-button type="text" @click="setContactState(scope.row, 3)">{{ $t('authModule.contactPerson.emptyNumber') }}</el-button>
            <el-button type="text" @click="setContactState(scope.row, 4)">{{ $t('authModule.contactPerson.knowNot') }}</el-button>
            <el-button type="text" @click="setContactState(scope.row, 5)">{{ $t('authModule.contactPerson.available') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-form ref="formValidate" :model="formValidate" :rules="rules" label-width="150px" class="demo-ruleForm" style="margin-top: 20px;">
      <el-form-item :label="$t('collectDetail.addPhone')" prop="phoneCall" style="max-height: 150px">
        <div style="max-height: 150px;overflow-y: auto">
          <el-row v-for="(item,index) in phoneArr" :key="index">
            <el-col :span="20">
              <el-input
                v-model="phoneArr[index]"
                clearable
                type="tel"
                :placeholder="$t('collectDetail.inputPhone')"
                :maxlength="20"
              />
            </el-col>
            <el-col :span="4">
              <i class="el-icon-remove" style="margin-left: 5px;font-size: 25px;line-height: 45px;color: #409EFF" @click="deletePhoneNum(index)" />
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-input
                v-model="phone"
                clearable
                type="tel"
                :placeholder="$t('collectDetail.inputPhone')"
                :maxlength="20"
              />
            </el-col>
            <el-col :span="4">
              <i class="el-icon-circle-plus" style="margin-left: 5px;font-size: 25px;line-height: 45px;color: #409EFF" @click="addPhoneNum" />
            </el-col>
          </el-row>
        </div>
      </el-form-item>
      <el-form-item :label="$t('collectDetail.messageContent')" prop="msg">
        <el-input
          v-model="formValidate.msg"
          type="textarea"
          :autosize="{ minRows: 4, maxRows: 6}"
          :placeholder="$t('collectDetail.messageContent')"
          :maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">{{ $t('common.operate.cancel') }}</el-button>
      <el-button type="primary" :loading="submitLoading" @click="handleSubmit">{{ $t('common.operate.sure') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { sendMsg } from '@/api/auth'
export default {
  name: 'SmsDialog',
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    userContactData: {
      type: Array,
      default: function() {
        return []
      }
    },
    phoneData: {
      type: Array,
      default: function() {
        return []
      }
    },
    staffData: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  data() {
    const validateExemption = (rule, value, callback) => {
      if (this.phoneArr.length === 0 && !this.phone) {
        callback(new Error(this.$t('collectDetail.inputPhone')))
      } else {
        callback()
      }
    }
    return {
      submitLoading: false,
      phone: null,
      multipleSelection: [],
      phoneArr: [],
      type: 1,
      formValidate: {
        phoneCall: null,
        msg: null
      },
      rules: {
        phoneCall: [{ required: true, validator: validateExemption, trigger: 'blur' }],
        msg: [{ required: true, message: this.$t('collectDetail.messageContent') + this.$t('common.null'), trigger: 'blur' }]
      }
    }
  },
  computed: {
    showState: {
      get: function() {
        return this.showDialog
      },
      set: function() {
      }
    }
  },
  mounted() {
    this.para = this.$route.query
  },
  methods: {
    handleClose() {
      this.$emit('change-dialog', 'isSms', false)
      setTimeout(() => {
        this.formValidate = {
          phoneCall: null,
          msg: null
        }
        this.phoneArr = []
      }, 10)
    },
    handleSubmit() {
      this.$refs['formValidate'].validate((valid) => {
        if (valid) {
          this.submitLoading = true
          const arr = [...new Set([...this.phoneArr, this.phone])]
          const data = {
            msgContent: this.formValidate.msg,
            orderId: this.para.orderId,
            operatorId: this.staffData['id'],
            operatorName: this.staffData['staffName'],
            phoneNumbers: arr
          }
          sendMsg(data)
            .then(res => {
              this.submitLoading = false
              if (res.success) {
                this.$message.success(this.$t('common.tips.operateSuccess'))
                this.handleClose()
              } else {
                this.$message.error(res.message)
              }
            })
            .catch(err => {
              this.$message.error(err.message)
              this.submitLoading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    setContactState(item, index) {
      this.$emit('set-contact-state', item, index)
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      this.multipleSelection.forEach(v => {
        this.phoneArr.push(v['contactPhone'])
      })
      this.phoneArr = [...new Set(this.phoneArr)]
    },
    deletePhoneNum(index) {
      const value = this.phoneArr[index]
      this.phoneArr.splice(index, 1)
      const item = this.multipleSelection.filter(v => {
        return v['contactPhone'] === value
      })
      if (item.length > 0) {
        item.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    addPhoneNum() {
      this.phoneArr.push(this.phone)
      this.phone = null
    },
    setType(type) {
      this.type = type
      setTimeout(() => {
        let items = []
        if (type === 1) {
          items = this.userContactData.filter(v => {
            return this.phoneArr.indexOf(v['contactPhone']) > -1
          })
        } else {
          items = this.phoneData.filter(v => {
            return this.phoneArr.indexOf(v['contactPhone']) > -1
          })
        }
        this.multipleSelection = items
        items.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      }, 100)
    }
  }
}
</script>

<style lang="scss" scoped>
  .el-select{
    width: 100%;
  }
  .admin-tree{
    margin-top: 20px;
  }
</style>
